
function removeMessage(el) {
    let msgBox = document.querySelector(".message-box");
    if (msgBox == null) {
        let msgBox = document.createElement('div');
        msgBox.className = 'message-box';
        document.body.appendChild(msgBox);
    }
    msgBox = document.querySelector(".message-box");

    el.style = 'animation: message-appear .3s reverse;animation-fill-mode:forwards';
    setTimeout((el => {
        el.style.padding = 0;
        el.style.height = 0;
        el.style.marginTop = 0;
        setTimeout((el) => { msgBox.removeChild(el);removeMessageBox() }, 1000, el);
        
    }), 400, el);

}
function removeMessageBox(){
    let message=document.querySelector('.message-item')
    if(!message){
        document.body.removeChild(document.querySelector('.message-box'))
    }
}
function addMessage(text, ...arr) {
    //检查messageBox是否存在
    let msgBox = document.querySelector(".message-box");
    if (msgBox == null) {
        let msgBox = document.createElement('div');
        msgBox.className = 'message-box';
        document.body.appendChild(msgBox);
    }
    msgBox = document.querySelector(".message-box");

    //初始化参数
    let title = null;
    let type = 1;
    //自动解析参数
    arr.forEach(item => {
        if (typeof (item) == 'number' && (item == 1 || item == 0)) {
            type = item;
        } else {
            title = item;
        }
    })
    let msg = {
        item: '',
        title: '',
        text: ''
    }
    //创建虚拟dom
    for (const key in msg) {
        if (Object.hasOwnProperty.call(msg, key)) {
            msg[key] = document.createElement('div')
        }
    }
    msg.item.className = `message-item ${type == 1 ? 'successMessage' : 'errorMessage'}`;
    //添加载入的动画
    msg.item.style = 'animation: message-appear .3s';
    msg.title.className = 'message-title';
    msg.title.innerText = title == null ? (type == 1 ? '成功' : '失败') : title;
    msg.text.className = 'message-text';
    msg.text.innerText = text;

    for (const key in msg) {
        if (Object.hasOwnProperty.call(msg, key)) {
            const element = msg[key];
            if (element === msg.item) {
                continue
            } else {
                msg.item.appendChild(element);
            }
        }
    }
    //添加点击事件监听
    msg.item.addEventListener('click', e => { removeMessage(e.target); })
    msgBox.appendChild(msg.item);
    //移除添加的载入动画，否则移除动画无效
    setTimeout((el) => { el.removeAttribute('style') }, 1000, msg.item);
    //添加自动消失
    setTimeout((el) => { removeMessage(el) }, 3000, msg.item);
}

export default addMessage